package com.stu.wgt.test.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.Admin;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.result.ResultCodeEnum;
import com.stu.wgt.test.service.AdminService;
import com.stu.wgt.test.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/Admin")
@CrossOrigin(origins = "http://localhost:8080")
public class AdminController {
    @Autowired
    AdminService adminService;

    //查看所有用户
    // http://localhost:8888/selectAllUser

    @GetMapping("/selectAllUser")
    public R selectAllUser() {
        try {
            List<Admin> adminList = adminService.selectAllUser();
            return R.ok().data("user", adminList).data("total", adminList.size());
        } catch (Exception e) {
            //发送错误的状态码
            return R.error().data("msg", "查找不到用户");
        }
    }

    //    分页查询
    @GetMapping("/search")
    public R searchUsers(@RequestParam("query") String query,
                         @RequestParam("pagenum") int pageNum,
                         @RequestParam("pagesize") int pageSize) {
        // 根据查询关键字、当前页数和每页显示的数据条数进行查询操作
        try {
            IPage<Admin> userIPage = adminService.searchUsers(query, pageNum, pageSize);
            return R.ok().data("user", userIPage.getRecords()).data("total", userIPage.getTotal());
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }


    // 根据用户ID查找用户
    @GetMapping("/user/{id}")
    public R getUsernameById(@PathVariable int id) {
        if (id <= 0) {
            return R.error().data("msg", "ID不能为空");
        }
        List<Admin> admin = adminService.selectById(id);
        if (admin.isEmpty()) {
            return R.error();
        }
        return R.ok().data("user", admin);
    }

    // 登录
    @RequestMapping("/login")
    public R login(@RequestBody Admin admin) {
        // 使用BCrypt加密算法对密码进行加密
        String md5Password = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        // 验证用户名和密码是否正确
        if (adminService.login(admin.getUsername(), md5Password)) {
            // 创建JWT并返回给客户端
            String token = JwtUtil.createToken("admin");
            // 获取用户数据
//            List<User> user1 =userService.selectByUsername(user.getUsername());
            return R.ok().data("token", token).data("user", admin);
        } else {
            return R.setResult(ResultCodeEnum.BAD_REQUEST);
        }
    }

    //增加用户(注册)
    @RequestMapping("/register")
    public R register(@RequestBody String requestBody) {
        Admin admin = JSON.parseObject(requestBody, Admin.class);
        String md5Pass = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        admin.setPassword(md5Pass);
        if (adminService.register(admin) == 1)
            return R.ok();
        return R.error().data("msg", "用户已存在请登录");
    }

    @DeleteMapping("/user/{id}")
    public R deleteUser(@PathVariable("id") Integer id) {
        // 调用UserService的删除用户的方法
        int success = adminService.deleteUser(id);

        if (success == 1) {
            return R.ok();
        } else {
            return R.setResult(ResultCodeEnum.BAD_REQUEST);
        }
    }

    @PutMapping("/user/{id}")
    public R updateUserRole(@PathVariable("id") Integer id, @RequestBody Admin admin) {
        // 从请求体中获取要更新的用户角色信息
        admin.setId(id);
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        // 调用UserService的更新用户角色的方法
        int success = adminService.updateUser(admin);

        if (success == 1) {
            return R.ok().data("message", "用户修改成功");
        } else {
            return R.setResult(ResultCodeEnum.BAD_REQUEST);
        }
    }

}

